package org.file5.dao.impl;

import org.apache.log4j.Logger;
import org.file5.dao.BaseDao;
import org.file5.dao.EntityIndexDao;
import org.file5.domain.BaseEntity;
import org.file5.domain.Entity2Entity;
import org.file5.domain.EntityIndex;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.google.appengine.api.datastore.QueryResultIterator;
import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;
import com.googlecode.objectify.Query;

@Repository("entityIndexDao")
public class EntityIndexDaoImpl implements EntityIndexDao {
	private final Logger logger = Logger.getLogger(this.getClass());

	@Autowired
	BaseDao baseDao;

	@Override
	public <E extends BaseEntity> EntityIndex<E> findByEntityKey(
			Key<E> entityKey) {
		if (entityKey != null) {
			Objectify ofy = ObjectifyService.begin();

			Query<EntityIndex> query = ofy.query(EntityIndex.class);

			query.filter("entityKey", entityKey);
			query.offset(0).limit(1);
			QueryResultIterator<EntityIndex> iterator = query.iterator();
			while (iterator.hasNext()) {
				return iterator.next();
			}
		}
		return null;
	}

	@Override
	public <E extends BaseEntity> EntityIndex<E> findUnIndexedEntity() {
		Objectify ofy = ObjectifyService.begin();

		Query<EntityIndex> query = ofy.query(EntityIndex.class);
		query.filter("indexed", 0);
		query.offset(0).limit(1);
		QueryResultIterator<EntityIndex> iterator = query.iterator();
		while (iterator.hasNext()) {
			return iterator.next();
		}
		return null;
	}

}
